package com.angcyo.selenium.auto.action

import com.angcyo.javafx.base.ex.syncBack
import com.angcyo.library.ex.count
import com.angcyo.selenium.auto.BaseControl
import com.angcyo.selenium.auto.controller.dslPutCode
import com.angcyo.selenium.auto.parse.HandleResult
import com.angcyo.selenium.auto.parse.args
import com.angcyo.selenium.bean.ActionBean
import org.openqa.selenium.WebElement

/**
 * Email:angcyo@126.com
 * @author angcyo
 * @date 2021/01/15
 */
class PutCodeAction : BaseCodeAction() {

    override fun interceptAction(control: BaseControl, action: String?): Boolean {
        return action?.startsWith(Action.ACTION_PUT_CODE) == true
    }

    override fun runAction(
        control: BaseControl,
        element: WebElement,
        actionBean: ActionBean,
        action: String
    ): HandleResult {
        val result = HandleResult()
        result.elementList = listOf(element)

        //解析参数
        var key = "imageCode"
        var imageArg: String? = null

        if (action.count(' ') > 0) {
            //如果包含了空格, 则使用最新的正则参数解析方法.
            imageArg = action.arg(Action.ACTION_PUT_CODE)
            key = action.arg("key") ?: key
        } else {
            action.args { index, str ->
                when (index) {
                    1 -> imageArg = str
                    2 -> key = str
                }
            }
        }

        //解析文本
        val textList = control._autoParse.parseText(control, imageArg)
        val text = textList.firstOrNull()

        //请求
        var value: String? = null
        if (!text.isNullOrEmpty()) {
            //调用api, 解析验证码
            val imageData = text.removeBase64Image()

            value = syncBack { dslPutCode(imageData) }

            saveCodeValue(control, result, key, value, imageData)
        }

        control.logAction?.invoke("输入验证码[$value]:${result.success}")
        return result
    }
}